#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import sys


def die(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)


def check_package_installed(package_dict, exit_or_return=True):
    ret = {}

    for distro, pkgMatcher in package_dict.items():
        if distro == "gentoo":
            if isinstance(pkgMatcher, list):    # it should be list<str>
                try:
                    import portage
                except ImportError:
                    continue
                vartree = portage.db[portage.root]["vartree"]
                for onePkgMatcher in pkgMatcher:
                    varCpvSet = set(vartree.dbapi.match(onePkgMatcher))
                    if len(varCpvSet) > 0:
                        ret.setdefault(distro, set()).update(varCpvSet)
                continue

            assert False

        assert False

    if len(ret) > 0:
        return ret
    else:
        if exit_or_return:
            sys.exit(0)
        else:
            return None
